package cn.fy.navigation.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;
import java.util.List;

import cn.fy.navigation.databinding.ActivityTabLayoutBinding;
import cn.fy.navigation.fragment.Frag1Fragment;
import cn.fy.navigation.fragment.Frag2Fragment;
import cn.fy.navigation.fragment.Frag3Fragment;

public class TabLayoutActivity extends AppCompatActivity {

    private ActivityTabLayoutBinding binding;

    private TabLayoutMediator tabLayoutMediator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_tab_layout);
        binding = ActivityTabLayoutBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("TabLayout Activity");

        ArrayList<String> listTitle = new ArrayList<>();
        listTitle.add("业务");
        listTitle.add("消息");
        listTitle.add("我的");

        List<Class> fragmentList = new ArrayList<>();
        fragmentList.add(Frag1Fragment.class);
        fragmentList.add(Frag2Fragment.class);
        fragmentList.add(Frag3Fragment.class);

        binding.viewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                //return listFragment.get(position);
                try {
                    return (Fragment) fragmentList.get(position).newInstance();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            public int getItemCount() {
                //return listFragment.size();
                return fragmentList.size();
            }
        });
        tabLayoutMediator = new TabLayoutMediator(binding.tabLayout, binding.viewPager, (tab, position) -> tab.setText(listTitle.get(position)));
        tabLayoutMediator.attach();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tabLayoutMediator.detach();
    }
}